package JPetStore.web.servlet;

import JPetStore.domain.Account;
import JPetStore.domain.Cart;
import JPetStore.domain.Item;
import JPetStore.persistence.CartDao;
import JPetStore.persistence.impl.CartDaoImpl;
import JPetStore.service.CatalogService;
import JPetStore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AddItemToCartServlet extends HttpServlet {

    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Cart cart = (Cart)session.getAttribute("cart");
        String workingItemId = req.getParameter("workingItemId");


        if(cart == null){
            cart = new Cart();
        }

        if (cart.containsItemId(workingItemId)) {
            cart.incrementQuantityByItemId(workingItemId);
        } else {
            CatalogService catalogService = new CatalogService();
            boolean isInStock = catalogService.isItemInStock(workingItemId);
            Item item = catalogService.getItem(workingItemId);
            cart.addItem(item, isInStock);
            Account loginAccount = (Account) session.getAttribute("loginAccount");
            if (loginAccount != null) {
                String username = loginAccount.getUsername();
                String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                        + req.getContextPath() + req.getServletPath() + "?" + (req.getQueryString());
                LogService logService = new LogService();
                String logInfo = logService.logInfo(new Object[]{" "}) + strBackUrl + "往购物车里添加了"+item.getItemId();
                logService.insertLogInfo(username, logInfo);
            }
        }
        try{
            Account loginAccount = (Account) session.getAttribute("loginAccount");
            CartDao cartDao = new CartDaoImpl();
            cartDao.deleteAll(loginAccount);
            cartDao.insertCart(cart.getCartItemList(),loginAccount);
        }catch (Exception e){
            e.printStackTrace();
        }
        session.setAttribute("cart", cart);

        req.getRequestDispatcher(CART_FORM).forward(req, resp);
    }
}